package com.controller;

import com.entity.VehicleInfo;
import com.service.VehicleInfoService;
import com.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/vehicle/info")
public class VehicleInfoController {

    @Autowired
    private VehicleInfoService vehicleInfoService;

    @PostMapping
    public VehicleInfo create(@RequestBody VehicleInfo vehicleInfo) {
        return vehicleInfoService.save(vehicleInfo);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable(value = "id") Integer id) {
        vehicleInfoService.deleteById(id);
    }

    @PutMapping("/{id}")
    public VehicleInfo update(@PathVariable(value = "id") Integer id, @RequestBody VehicleInfo vehicleInfo) {
        vehicleInfo.setId(id);
        return vehicleInfoService.save(vehicleInfo);
    }

    @GetMapping("/{id}")
    public VehicleInfo detail(@PathVariable(value = "id") Integer id) {
        return vehicleInfoService.findById(id).orElse(null);
    }

    @GetMapping("/page")
    public Page<VehicleInfo> page(@RequestParam(defaultValue = "1") int pageNum,
                       @RequestParam(defaultValue = "10") int pageSize,
                       @RequestParam(required = false) String plateNumber) {
        Page<VehicleInfo> page;
        if (plateNumber != null && !plateNumber.isEmpty()) {
            page = vehicleInfoService.findByPlateNumberContaining(plateNumber, pageNum, pageSize);
        } else {
            page = vehicleInfoService.findAll(pageNum, pageSize);
        }
        return page;
    }
}